package com.gzmu.face.config;


import com.alibaba.fastjson.JSONObject;
import com.gzmu.face.tools.HttpResult;
import com.gzmu.face.tools.HttpUtil;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.Random;

/**
 * Created by Hyman on 2017/2/28.
 */
public class CommonUtil {
    static final int wdDoNotSaveChanges = 0;// 不保存待定的更改。
    static final int wdFormatPDF = 17;// word转PDF 格式

    public static String getRandomOrderId() {
        // UUID.randomUUID().toString().replace("-","")
        Random random = new Random(System.currentTimeMillis());
        int value = random.nextInt();
        while (value < 0) {
            value = random.nextInt();
        }
        return value + "";
    }

    /**
     * 对字符串md5加密
     *
     * @param str
     * @return
     */
    public static String getMD5(String str) throws Exception {
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 计算md5函数
            md.update(str.getBytes());
            // digest()最后确定返回md5 hash值，返回值为8为字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
            return new BigInteger(1, md.digest()).toString(16);
        } catch (Exception e) {
            throw new Exception("MD5加密出现错误");
        }
    }


    public static String getOpenid(String code, String appid, String appsecret) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid +
                "&secret=" + appsecret + "&js_code=" + code + "&grant_type=authorization_code";
        HttpUtil httpUtil = new HttpUtil();
        try {
            HttpResult httpResult = httpUtil.doGet(url, null, null);
            if(httpResult.getStatusCode() == 200) {
                JSONObject obj = JSONObject.parseObject(httpResult.getBody());
                System.out.println("+++obj: " + obj.toString());

                if(obj.get("errcode") != null) {
                    System.out.println("+++obj returns errcode: " + obj.get("errcode"));
                    return null;
                } else {
                    return obj.get("openid").toString();
                }
                //return httpResult.getBody();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
